//
//  JoinCheDuiViewController.m
//  Rabbit
//
//  Created 阿帕 on 2019/12/18.
//  Copyright © 2019 GCY. All rights reserved.
//

#import "JoinedCheDuiViewController.h"
#import "CYWebViewViewController.h"
#import "XieYiListViewController.h"
#import "CarTeamJoinedCell.h"

@interface JoinedCheDuiViewController ()<UITableViewDataSource, UITableViewDelegate, JoinedTeamButtonDelegate>

@property (strong , nonatomic)UITextField *textFiled;

@property (strong , nonatomic)UITableView *tableView;

@property (strong , nonatomic)NSMutableArray *dataArray;

@property (strong , nonatomic)UIImageView *foundImageView;

@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation JoinedCheDuiViewController

static const CGFloat cellHeight = 171;

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _pageNum = 1;
    
    [self setupBaseView];
}

- (void)setupBaseView {
    
    self.navigationItem.title = @"已加入车队列表";

    self.view.backgroundColor = BackgroundColor;
    
    _textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 10, ScreenW, 40)];
    _textFiled.font = font(14);
    _textFiled.text = @"";
    _textFiled.backgroundColor = [UIColor whiteColor];
    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textFiled.keyboardType = UIKeyboardTypeDefault;
    _textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"车队名称/手机号/联系人" attributes:@{NSForegroundColorAttributeName: Light_TextColor}];
    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 15, 40)];
    _textFiled.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 40)];
    _textFiled.leftViewMode = UITextFieldViewModeAlways;
    [_textFiled addSubview: leftView];
    
    
    UIImageView *searchImage = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenW-40, 10, 20, 20)];
    searchImage.userInteractionEnabled = YES;
    searchImage.image = [UIImage imageNamed:@"gcy_icon_search_siji"];
    _textFiled.rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    _textFiled.rightViewMode = UITextFieldViewModeAlways;
    [_textFiled addSubview:searchImage];
    
    [searchImage nyl_addTapGes:^{
        _pageNum = 1;
        [self carTeamJoinedListRequest];
    }];
    
    [self.view addSubview:_textFiled];
    
    [self.view addSubview:self.tableView];

    [self carTeamJoinedListRequest];
}

- (void)carTeamJoinedListRequest {
    WEAKSELF
    
    if (_pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    NSDictionary *params = @{
        @"pageSize":DEFULT_LOAD_NUM,
        @"pageNum":[NSNumber numberWithInteger:_pageNum],
        @"searchInfo": _textFiled.text,
        @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
    };
    
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], DRIVER_JOINEDTEAMLIST) withParameter:params withVC:self netName:@"已加入车队列表" success:^(id response, NSString *msg) {
        
        if ([response[@"records"] count] != 0) {
            [weakSelf.dataArray addObjectsFromArray:[CarTeamModel mj_objectArrayWithKeyValuesArray:response[@"records"]]];
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
            
            weakSelf.foundImageView.hidden = YES;
            weakSelf.tableView.hidden = NO;
            
        }else{
            if (_pageNum == 1) {
                weakSelf.foundImageView.hidden = NO;
                weakSelf.tableView.hidden = YES;
            }
            
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            
        }
        
        [weakSelf.tableView reloadData];
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

#pragma mark - JoinedTeamButtonDelegate
- (void)buttonIndexClick:(NSInteger)index withButton:(UIButton *)button {
    
    WEAKSELF
    
    NSString *title = button.titleLabel.text;
    
    NSIndexPath *indexpath = [self.tableView indexPathForRowAtPoint:[self.tableView convertPoint:button.center fromView:button.superview]];
    DebugLog(@"点击了第%ld个item的第%ld个按钮",(long)indexpath.row, (index-99));
    
    CarTeamModel *crModel = self.dataArray[indexpath.row];

    if ([title isEqual:@"添加代收协议"]) {
        
        CYWebViewViewController *webVC = [[CYWebViewViewController alloc] init];
        webVC.titleString = @"代收协议";
        webVC.urlString = [NSString stringWithFormat:@"%@/admin/#/collectionAgreement4Mobile?code=%@&type=new", BasicDomainURL, crModel.acceptCode];
        webVC.state = 3;
        [self.navigationController pushViewController:webVC animated:YES];
        
        webVC.XieYiBlock = ^(NSInteger index) {
            if (index == 1) {
                [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@/%@", [NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], ACCEPTVEHICLE_ACCEPT, crModel.acceptCode) withParameter:@{@"token":[UserDefaultUtil valueForKey:USER_TOKEN],} withVC:self netName:@"添加代收协议" success:^(id response, NSString *msg) {
                    
                    [XSInfoView showInfo:msg onView:weakSelf.view];
                    
                    
                } failure:^(NSInteger code, NSString *msg) {
                    
                }];
            }
        };
        
    } else if ([title isEqual:@"协议记录"]) {
        
        XieYiListViewController *xylvc = [[XieYiListViewController alloc] init];
        xylvc.acceptCode = crModel.acceptCode;
        [self.navigationController pushViewController:xylvc animated:YES];
        
    } else if ([title isEqual:@"退出车队"]) {
        
        [DCSpeedy dc_SetUpAlterWithView:self Title:@"" Message:@"确定要退出车队吗？" Sure:^{
            
            NSDictionary *params = @{@"teamCode": crModel.partyCode,@"token":[UserDefaultUtil valueForKey:USER_TOKEN],};
            
            [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], ACCEPTVEHICLE_EXITTEAM) withParameter:params withVC:self netName:@"退出车队" success:^(id response, NSString *msg) {
                
                [XSInfoView showInfo:@"退出车队成功" onView:weakSelf.view];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
                
            } failure:^(NSInteger code, NSString *msg) {
                
            }];
            
        } Cancel:^{
            
        }];
    }
}

//上拉刷新数据
- (void)loadNewData{
    _pageNum = 1;
    [self carTeamJoinedListRequest];
}
- (void)loadMoreData{
    _pageNum ++;
    [self carTeamJoinedListRequest];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CarTeamJoinedCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    cell.model = self.dataArray[indexPath.row];
    
    cell.teamTelButton.tag = indexPath.row + 200;
    
    NSInteger driverType = [[UserDefaultUtil valueForKey:DRIVER_TYPE] integerValue];
    if (driverType == 0) {
        //独立司机
        cell.exitCarTeamButton.hidden = NO;
//        [cell.exitCarTeamButton addTarget:self action:@selector(exitCarTeamBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//        cell.exitCarTeamButton.tag = indexPath.row + 300;

    } else {
        //车队司机
        cell.exitCarTeamButton.hidden = YES;
    }
    [cell.teamTelButton addTarget:self action:@selector(telBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
    
}

- (void)telBtnClick:(UIButton *)sender {
    
    CarTeamModel *crModel = self.dataArray[sender.tag-200];
    CALL_PHONE(crModel.phone);
    
}

- (void)exitCarTeamBtnClick:(UIButton *)sender {
    
    
    
    
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return cellHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark - LazyLoad
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.frame = CGRectMake(0, 51, ScreenW, ScreenH - NavHeight - 51);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        //注册单元格
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CarTeamJoinedCell class]) bundle:nil] forCellReuseIdentifier:@"CellID"];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (UIImageView *)foundImageView {
    if (!_foundImageView) {
        _foundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 170, 170)];
        _foundImageView.image = image(@"gcy_img_list_found");
        _foundImageView.contentMode = UIViewContentModeScaleAspectFit;
        _foundImageView.cy_centerX = self.view.cy_centerX;
        _foundImageView.cy_centerY = self.view.cy_centerY;
        [self.view addSubview:_foundImageView];
    }
    return _foundImageView;
}

@end
